package com.yvan.codeslave;

import com.yvan.codeslave.batch.util;
import com.yvan.codeslave.snippet.Idea;
import lombok.SneakyThrows;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.resource.FileResourceLoader;
import org.beetl.core.resource.MapResourceLoader;
import org.beetl.core.resource.StringTemplateResourceLoader;

import java.util.Map;

public class BeetlUtils {

    @SneakyThrows
    private static Configuration createConfiguration() {
        Configuration cfg = Configuration.defaultConfiguration();
        //cfg.setErrorHandlerClass("com.yvan.codeslave.IdeaErrorHandle");
        return cfg;
    }

    private static void initTemplate(GroupTemplate groupTemplate) {
        groupTemplate.setErrorHandler(new IdeaErrorHandle());
        groupTemplate.registerFunctionPackage("util", util.class);
        groupTemplate.registerFunctionPackage("idea", Idea.class);
    }

    public static GroupTemplate createSnippetGroupTemplate(Map<String, String> templates) {

        MapResourceLoader resourceLoader = new MapResourceLoader();
        resourceLoader.putAll(templates);
        Configuration cfg = createConfiguration();

        GroupTemplate mapGroupTemplate = new GroupTemplate(resourceLoader, cfg);
        initTemplate(mapGroupTemplate);

        return mapGroupTemplate;
    }

    public static GroupTemplate createStringGroupTemplate() {
        StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
        Configuration cfg = createConfiguration();

        GroupTemplate stringGroupTemplate = new GroupTemplate(resourceLoader, cfg);
        initTemplate(stringGroupTemplate);

        return stringGroupTemplate;
    }

    public static GroupTemplate createFileSystemGroupTemplate(String rootPath) {
        FileResourceLoader resourceLoader = new FileResourceLoader();
        resourceLoader.setAutoCheck(true);
        resourceLoader.setCharset("UTF-8");
        resourceLoader.setRoot(rootPath);

        Configuration cfg = createConfiguration();
        GroupTemplate templateEngin = new GroupTemplate(resourceLoader, cfg);
        initTemplate(templateEngin);

        return templateEngin;
    }
}
